import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;

public class Processor extends Thread {

	private Socket socket;
	private InputStream in;
	private PrintStream out;
	public final static String WEB_ROOT = "c:\\test";

	public Processor(Socket socket) {
		this.socket = socket;
		try {
			//处理输入流
			in = socket.getInputStream();
			out = new PrintStream(socket.getOutputStream());
		} catch (IOException e) {
			System.out.println("processor 错误原因：" + e.getMessage());
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	/**
	 * 启动线程
	 */
	public void run() {
		String filename = parse(in);
		sendFile(filename);
	}
	/**
	 * 输入输出流的方法的处理
	 * @param in
	 * @return
	 */
	public String parse(InputStream in) {
		BufferedReader br = new BufferedReader(new InputStreamReader(in));
		String filename = null;

		try {
			String httpMsg = br.readLine();
			String[] content = httpMsg.split(" ");
			if (content.length != 3) {
				sendErrorMsg(400, "Client query error!");
				return null;
			}
			System.out.println("code:" + content[0] + ",filename:" + content[1]
					+ ",http version" + content[2]);
			filename = content[1];
		} catch (IOException e) {
			System.out.println("parse错误信息：" + e.getMessage());
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return filename;
	}
	/**
	 * 发送错误信息
	 * @param errorcode
	 * @param errorMsg
	 */
	public void sendErrorMsg(int errorcode, String errorMsg) {
		out.println("HTTP/1.0" + errorcode + " " + errorMsg);
		out.println("content-type:text/html");
		out.println();
		out.println("<html>");
		out.println("<title>Error Msg");
		out.println("</title>");
		out.println("<body>");
		out.println("<h1>errorcode:" + errorcode + ",ErrorMsg:" + errorMsg);
		out.println("</h1>");
		out.println("</body>");
		out.println("</html>");
		out.flush();
		out.close();
		try {
			in.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	/**
	 * 解析正常返回正常信息
	 * @param filename
	 */
	public void sendFile(String filename) {
		File file = new File(Processor.WEB_ROOT + filename);
		if (!file.exists()) {
			sendErrorMsg(404, "File not found!");
			return;
		}
		try {
			InputStream in = new FileInputStream(file);
			byte content[] = new byte[(int) file.length()];
			in.read(content);
			out.println("HTTP/1.0 200 SENDFILE query sucess");
			out.println("content-length" + content.length);
			out.println();
			out.write(content);
			out.flush();
			out.close();
			in.close();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
